package cn.yunyichina.openapi.proxy.utils;

import cn.yunyichina.openapi.proxy.entity.Response;
import cn.yunyichina.utils.convert.JsonUtils;

import com.alibaba.dubbo.common.utils.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpServerUtil {

    public static boolean isEmpty(String s) {
        return (s == null) || ("".equals(s.trim()));
    }

    /**
     * 根据传入的方法名，找到对应的服务定义
     *
     * @param method
     * @return
     */
    public static String getServiceDefine(String method) {
        String result = "";
        String[] strs = method.split("\\.");
        if (strs.length > 2) {
            result = strs[1];
            result = "I" + result.substring(0, 1).toUpperCase() + result.substring(1);
        }
        return result;
    }

    /**
     * 组合回调方法  https://localhost/base/user/login/font 或者 back--->yyt.base.user.login
     *
     * @param urlSplits
     * @return
     * @throws Exception
     */
    public static String getMethod(String[] urlSplits) throws Exception {
        return StringUtils.join(urlSplits, ".");
    }

    /**
     * Map的转换
     *
     * @param maps
     * @return
     * @throws Exception
     */
    public static Map<String, String> convertMaplistToMap(Map<String, List<String>> maps) throws Exception {
        Map<String, String> params = new HashMap<>();
        if (!maps.isEmpty()) {
            for (Entry<String, List<String>> p : maps.entrySet()) {
                String key = p.getKey().trim();
                List<String> vals = p.getValue();
                if (vals.size() == 0) {
                    String error = JsonUtils.toJsonString(new Response("7", "参数不能为空"));
                    throw new RuntimeException(error);
                }

                if (vals.size() > 1) {
                    String error = JsonUtils.toJsonString(new Response("8", "重复参数错误"));
                    throw new RuntimeException(error);
                }
                params.put(key, vals.get(0).trim());
            }
        }
        return params;
    }

}
